package valve_test.forms;

import valve_test.DAO.Factory;
import valve_test.drawning.graph_pane;
import valve_test.logic.*;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Shinigami
 * Date: 13.03.14
 * Time: 16:26
 * To change this template use File | Settings | File Templates.
 */
public class add_valve {
    private JPanel add_valve_panel;
    private JButton bt_cancel;
    private JButton bt_add;
    private JTextField textField1;
    private JPanel cb_panel1;
    private JTextField input_field;
    private JTextField output_field;
    private JFrame frame;
    ImageIcon icon_add = new ImageIcon("Add.png");
    ImageIcon icon_rem = new ImageIcon("Rem.png");
    private int i = 0;


    public add_valve(final valves v, Point cf) {
        frame = new JFrame("Список вентилей");
        frame.getContentPane().add(add_valve_panel);
        frame.setSize(420, 600);
        frame.setLocation(cf.x+520,cf.y);
        frame.setVisible(true);
        cb_panel1.setLayout(null);
        JLabel l = new JLabel();
        l.setText("Parent");
        l.setLocation(175, 5);
        cb_panel1.add(l);
        fill_cb_panel1();
        if (v.getv_id() != -1){
            textField1.setText(v.getv_name());
            textField1.setEnabled(false);
            input_field.setText(v.getinput().toString());
            output_field.setText(v.getoutput().toString());
            try {
                List<ierarchy> ies = new ArrayList<ierarchy>();
                ies = Factory.getInstance().getIerarchyDAO().getIerarchiesByChild(v.getv_id());
                i = ies.size();
                fill_cb_panel1();
                int f = 0;
                Boolean fl1 = false;
                Boolean fl2 = false;
                for (int a = 0; a < i; a++)
                {
                    if (f != i){
                        Component[] comp= cb_panel1.getComponents();
                        for (Component com : comp)
                        {
                            if (com instanceof JComboBox)
                            {
                                if (com.getName().equals("name"+f)){
                                    JComboBox cbt = (JComboBox) com ;
                                    cbt.addItemListener(new ActionChangeSelection1());
                                    cbt.setSelectedItem(Factory.getInstance().getValvesDAO().getValveById(ies.get(f).getP_id()).getv_name());
                                    f++;
                                }
                            }
                        }
                    }
                }
                f = 0;
                fl1 = false;
                fl2 = false;
                for (int a = 0; a < i; a++)
                {
                    if (f != i){
                        Component[] comp= cb_panel1.getComponents();
                        for (Component com : comp)
                        {
                            if (com instanceof JComboBox)
                            {
                                if (com.getName().equals("p_o"+f)){
                                    JComboBox cbt = (JComboBox) com ;
                                    cbt.setSelectedIndex(ies.get(f).getP_o().intValue()-1);
                                    fl1 = true;
                                }
                                if (com.getName().equals("c_i"+f)){
                                    JComboBox cbt = (JComboBox) com ;
                                    cbt.setSelectedIndex(ies.get(f).getC_i().intValue()-1);
                                    fl2 = true;
                                }
                                if (fl1&&fl2){
                                    f++;
                                    fl1 = false;
                                    fl2 = false;
                                }
                            }
                        }
                    }
                }
                frame.repaint();
            }
            catch (SQLException ex){
                System.out.println(ex.toString());
                System.exit(-1);
            }

            bt_add.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        if (textField1.getText().equals(""))  JOptionPane.showMessageDialog  (null, "Введите имя вентиля", "Ошибка", JOptionPane.OK_OPTION);
                        else{
                            v.setInput(Long.parseLong(input_field.getText().toString()));
                            v.setOutput(Long.parseLong(output_field.getText().toString()));
                            if (validate_valve(v)){
                                Factory.getInstance().getValvesDAO().updateValve(v);
                                ierarchy ierarch = new ierarchy();
                                ierarch.setC_id(v.getv_id());
                                List<ierarchy> ies_add = new ArrayList<ierarchy>();
                                if (i != 0) {
                                    int f = 0;
                                    Boolean fl1 = false;
                                    Boolean fl2 = false;
                                    Boolean fl3 = false;
                                    for (int a = 0; a < i; a++) {
                                        if (f != i) {
                                            Component[] comp = cb_panel1.getComponents();
                                            for (Component com : comp) {
                                                if (com instanceof JComboBox) {
                                                    if (com.getName().equals("name" + f)) {
                                                        JComboBox cbt = (JComboBox) com;
                                                        ierarch.setP_id(Factory.getInstance().getValvesDAO().getValveByName(cbt.getSelectedItem().toString()).getv_id());
                                                        fl1 = true;
                                                    }
                                                    if (com.getName().equals("p_o" + f)) {
                                                        JComboBox cbt = (JComboBox) com;
                                                        ierarch.setP_o(Long.parseLong(cbt.getSelectedItem().toString()));
                                                        fl2 = true;
                                                    }
                                                    if (com.getName().equals("c_i" + f)) {
                                                        JComboBox cbt = (JComboBox) com;
                                                        ierarch.setC_i(Long.parseLong(cbt.getSelectedItem().toString()));
                                                        fl3 = true;
                                                    }
                                                    if (fl1 && fl2 && fl3) {
                                                        ies_add.add(ierarch);
                                                        ierarch = new ierarchy();
                                                        ierarch.setC_id(v.getv_id());
                                                        f++;
                                                        fl1 = false;
                                                        fl2 = false;
                                                        fl3 = false;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                if (validate_ierarchies(ies_add)){
                                    List<ierarchy> is = Factory.getInstance().getIerarchyDAO().getIerarchiesByChild(v.getv_id());
                                    for (int z = 0; z < is.size(); z++)
                                        Factory.getInstance().getIerarchyDAO().deleteIerarchy(is.get(z));
                                    for (int a = 0; a < ies_add.size(); a++)
                                        Factory.getInstance().getIerarchyDAO().addIerarchy(ies_add.get(a));
                                    graph_pane.ies = null;
                                    graph_pane.vs = null;
                                    frame.setVisible(false);
                                    control.ViewValvesForm();
                                }
                            }
                        }
                    }
                    catch (SQLException ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }
        else{
            bt_add.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        if (textField1.getText().equals(""))
                            JOptionPane.showMessageDialog(null, "Введите имя вентиля", "Ошибка", JOptionPane.OK_OPTION);
                        else {
                            v.setV_name(textField1.getText());
                            v.setInput(Long.parseLong(input_field.getText().toString()));
                            v.setOutput(Long.parseLong(output_field.getText().toString()));
                            v.setV_id(null);
                            if (validate_valve(v)) {
                                ierarchy ierarch = new ierarchy();
                                ierarch.setC_id(v.getv_id());
                                List<ierarchy> ies_add = new ArrayList<ierarchy>();
                                if (i != 0) {
                                    int f = 0;
                                    Boolean fl1 = false;
                                    Boolean fl2 = false;
                                    Boolean fl3 = false;
                                    for (int a = 0; a < i; a++) {
                                        if (f != i) {
                                            Component[] comp = cb_panel1.getComponents();
                                            for (Component com : comp) {
                                                if (com instanceof JComboBox) {
                                                    if (com.getName().equals("name" + f)) {
                                                        JComboBox cbt = (JComboBox) com;
                                                        ierarch.setP_id(Factory.getInstance().getValvesDAO().getValveByName(cbt.getSelectedItem().toString()).getv_id());
                                                        fl1 = true;
                                                    }
                                                    if (com.getName().equals("p_o" + f)) {
                                                        JComboBox cbt = (JComboBox) com;
                                                        ierarch.setP_o(Long.parseLong(cbt.getSelectedItem().toString()));
                                                        fl2 = true;
                                                    }
                                                    if (com.getName().equals("c_i" + f)) {
                                                        JComboBox cbt = (JComboBox) com;
                                                        ierarch.setC_i(Long.parseLong(cbt.getSelectedItem().toString()));
                                                        fl3 = true;
                                                    }
                                                    if (fl1 && fl2 && fl3) {
                                                        ies_add.add(ierarch);
                                                        ierarch = new ierarchy();
                                                        ierarch.setC_id(v.getv_id());
                                                        f++;
                                                        fl1 = false;
                                                        fl2 = false;
                                                        fl3 = false;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                if (validate_ierarchies(ies_add)){
                                    Factory.getInstance().getValvesDAO().addValve(v);
                                    for (int a = 0; a < ies_add.size(); a++){
                                        ies_add.get(a).setC_id(v.getv_id());
                                        Factory.getInstance().getIerarchyDAO().addIerarchy(ies_add.get(a));
                                    }
                                    graph_pane.ies = null;
                                    graph_pane.vs = null;
                                    frame.setVisible(false);
                                    control.ViewValvesForm();
                                }
                            }
                        }
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }

        bt_cancel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.setVisible(false);
            }
        });

        input_field.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void changedUpdate(DocumentEvent e) {
                updateLabel(e);
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                updateLabel(e);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                updateLabel(e);
            }

            private void updateLabel(DocumentEvent e) {
                EventQueue.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        if (Integer.parseInt(input_field.getText()) < 0 ){
                            JOptionPane.showMessageDialog(null, "Отрицательное количество входов", "Ошибка", JOptionPane.OK_OPTION);
                            input_field.setText("0");
                        }
                        if (i > Integer.parseInt(input_field.getText())) i = Integer.parseInt(input_field.getText());
                        rem_sel();
                    }
                });
            }
        });

        output_field.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void changedUpdate(DocumentEvent e) {
                updateLabel(e);
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                updateLabel(e);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                updateLabel(e);
            }

            private void updateLabel(DocumentEvent e) {
                EventQueue.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        if (Integer.parseInt(output_field.getText()) < 0 ){
                            JOptionPane.showMessageDialog(null, "Отрицательное количество выходов", "Ошибка", JOptionPane.OK_OPTION);
                            output_field.setText("0");
                        }
                        rem_sel();
                    }
                });
            }
        });
    }

    public void fill_cb_panel1(){
        cb_panel1.removeAll();
        JLabel l = new JLabel();
        l.setText("Parents");
        l.setSize(100, 20);
        l.setLocation(175, 0);
        cb_panel1.add(l);
        l = new JLabel();
        l.setText("От какого вентиля");
        l.setSize(150, 20);
        l.setLocation(150, 20);
        cb_panel1.add(l);
        l = new JLabel();
        l.setText("От какого выхода");
        l.setSize(150, 20);
        l.setLocation(295, 20);
        cb_panel1.add(l);
        l = new JLabel();
        l.setText("К какому входу");
        l.setSize(100, 20);
        l.setLocation(10, 20);
        cb_panel1.add(l);
        try {
            List<valves> valvs = Factory.getInstance().getValvesDAO().getAllValves();
            for (int a = 0; a < i; a++){
                JComboBox cb = new JComboBox();
                cb.setSize(70,20);
                cb.setName("name" + a);
                cb.setLocation(165,50 + 22 * a );
                for (int b = 0; b < valvs.size() ; b++){
                    if (valvs.get(b).getoutput() != 0)
                        cb.addItem(valvs.get(b).getv_name());
                    }
                cb.addItemListener(new ActionChangeSelection1());
                cb_panel1.add(cb);
                valves vp = Factory.getInstance().getValvesDAO().getValveByName(cb.getSelectedItem().toString());
                cb = new JComboBox();
                cb.setSize(70,20);
                cb.setName("p_o"+a);
                cb.setLocation(315,50 + 22 * a );
                for (int b = 0; b < vp.getoutput(); b++){
                    cb.addItem(b+1);
                }
                cb_panel1.add(cb);
                cb = new JComboBox();
                cb.setSize(70,20);
                cb.setName("c_i"+a);
                cb.setLocation(20,50 + 22 * a );
                for (int b = 0; b < Integer.parseInt(input_field.getText()); b++){
                    cb.addItem(b+1);
                }
                cb_panel1.add(cb);
            }
            JButton bt=new JButton(icon_add);
            bt.setSize(50,30);
            bt.setLocation(100, 60 + 22 * i);
            bt.addActionListener(new ActionAddButton1());
            cb_panel1.add(bt);
            bt=new JButton(icon_rem);
            bt.setSize(50,30);
            bt.setLocation(250, 60 + 22 * i);
            bt.addActionListener(new ActionAddButton2());
            cb_panel1.add(bt);
            frame.repaint();
        }
        catch (SQLException ex) {
            ex.printStackTrace();
        }
    };


    private class ActionAddButton1 implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (i < Integer.parseInt(input_field.getText()))
                i++;
            rem_sel();
        }
    }

    private class ActionChangeSelection1 implements ItemListener {
        @Override
        public void itemStateChanged(ItemEvent event) {
            if (event.getStateChange() == ItemEvent.SELECTED){
                combo_change();
            }
        }
    }

    private class ActionAddButton2 implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (i > 0)
                i--;
            rem_sel();
        }
    }

    private void combo_change(){
        try {
            int f = 0;
            String tstr = "", str = "";
            Component[] comp= cb_panel1.getComponents();
            boolean f1 = false;
            for (int j = 0; j < i; j++){
                for (Component com : comp)
                {
                    if (com instanceof JComboBox)
                    {
                        if (com.getName().equals("p_o"+f) && f1)
                        {
                            JComboBox cbt = (JComboBox) com ;
                            tstr = cbt.getSelectedItem().toString();
                            valves vp = Factory.getInstance().getValvesDAO().getValveByName(str);
                            cbt.removeAllItems();
                            for (int b = 0; b < vp.getoutput(); b++){
                                cbt.addItem(b+1);
                            }
                            if (cbt.getItemCount() >= Integer.parseInt(tstr))
                                cbt.setSelectedIndex(Integer.parseInt(tstr)-1);
                            else
                            cbt.setSelectedIndex(0);
                            f++;
                            f1 = false;
                        }
                        if (com.getName().equals("name"+f) && !f1)
                        {
                            JComboBox cbt = (JComboBox) com ;
                            valves vp = Factory.getInstance().getValvesDAO().getValveByName(cbt.getSelectedItem().toString());
                            str = cbt.getSelectedItem().toString();
                            f1 = true;
                        }
                    }
                }
            }
        }
        catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    private void rem_sel(){
        try{
            Component[] comp= cb_panel1.getComponents();
            int f = 0;
            List<ierarchy> il = new ArrayList<ierarchy>();
            ierarchy ti = new ierarchy();
            boolean f1 = false, f2 = false, f3 = false;
            for (int z = 0; z < 7; z++){
                for (Component com : comp)
                {
                    if (com instanceof JComboBox)
                    {
                        if (com.getName().equals("p_o"+f))
                        {
                            JComboBox cbt = (JComboBox) com;
                            ti.setP_o(Long.parseLong(cbt.getSelectedItem().toString()));
                            f1 = true;
                        }
                        if (com.getName().equals("name"+f))
                        {
                            JComboBox cbt = (JComboBox) com;
                            ti.setP_id(Factory.getInstance().getValvesDAO().getValveByName(cbt.getSelectedItem().toString()).getv_id());
                            f2 = true;
                        }
                        if (com.getName().equals("c_i"+f))
                        {
                            JComboBox cbt = (JComboBox) com;
                            ti.setC_i(Long.parseLong(cbt.getSelectedItem().toString()));
                            f3 = true;
                        }
                        if (f1 && f2 && f3){
                            f++;
                            f1 = false;
                            f2 = false;
                            f3 = false;
                            il.add(ti);
                            ti = new ierarchy();
                        }
                    }
                }
            }
            cb_panel1.removeAll();
            fill_cb_panel1();
            comp = cb_panel1.getComponents();
            f = 0;
            for (int z = 0; z < 7; z++){
                for (Component com : comp)
                {
                    if (f < il.size()){
                        if (com instanceof JComboBox)
                        {
                            if (com.getName().equals("name"+f))
                            {
                                JComboBox cbt = (JComboBox) com;
                                cbt.setSelectedItem(Factory.getInstance().getValvesDAO().getValveById(il.get(f).getP_id()).getv_name());
                                f2 = true;
                            }
                            if (f2){
                                f++;
                                f2 = false;
                            }
                        }
                    }
                }
            }
            comp= cb_panel1.getComponents();
            f = 0;
            for (int z = 0; z < 7; z++){
                for (Component com : comp)
                {
                    if (f < il.size()){
                        if (com instanceof JComboBox)
                        {
                            if (com.getName().equals("p_o"+f))
                            {
                                JComboBox cbt = (JComboBox) com;
                                cbt.setSelectedIndex(Integer.parseInt(il.get(f).getP_o().toString())-1);
                                f1 = true;
                            }
                            if (com.getName().equals("c_i"+f))
                            {
                                JComboBox cbt = (JComboBox) com;
                                cbt.setSelectedIndex(Integer.parseInt(il.get(f).getC_i().toString())-1);
                                f3 = true;
                            }
                            if (f1 && f3){
                                f++;
                                f1 = false;
                                f3 = false;
                            }
                        }
                    }
                }
            }
        }
        catch (SQLException ex){
            ex.printStackTrace();
        }
    }

    private boolean validate_valve(valves v){
        if (v.getoutput() < 0){
            JOptionPane.showMessageDialog(null, "Отрицательное количество выходов", "Ошибка", JOptionPane.OK_OPTION);
            return false;
        }
        if (v.getinput() < 0){
            JOptionPane.showMessageDialog(null, "Отрицательное количество входов", "Ошибка", JOptionPane.OK_OPTION);
            return false;
        }
        if (v.getv_id() == null){
            try {
                valves tv = Factory.getInstance().getValvesDAO().getValveByName(v.getv_name());
                if (tv != null){
                    JOptionPane.showMessageDialog(null, "Вентиль с таким именем уже существует", "Ошибка", JOptionPane.OK_OPTION);
                    return false;
                }
            }
            catch (SQLException ex){
            //
            }
        }
        return true;
    }

    private boolean validate_ierarchies(List<ierarchy> i_add){
        try{
            List<ierarchy> ies = new ArrayList<ierarchy>();
            if (i_add.size() >= 2){
                for (int a = 0; a < i_add.size() - 1; a++){
                    for (int b = a + 1; b < i_add.size(); b++){
                        if (i_add.get(a).getC_i() == i_add.get(b).getC_i()){
                            JOptionPane.showMessageDialog(null, "Вход №" + i_add.get(a).getC_i().toString() + " указан несколько раз", "Ошибка", JOptionPane.OK_OPTION);
                            return false;
                        }
                        if (i_add.get(a).getP_id() == i_add.get(b).getP_id()){
                            if (i_add.get(a).getP_o() == i_add.get(b).getP_o()){
                                JOptionPane.showMessageDialog(null, "Выход №" + i_add.get(a).getP_o().toString() + " у " + Factory.getInstance().getValvesDAO().getValveById(i_add.get(a).getP_id()).getv_name().toString() + " указан несколько раз", "Ошибка", JOptionPane.OK_OPTION);
                                return false;
                            }
                        }
                    }
                }
            }
            if (i_add.size() > 0)
                ies = Factory.getInstance().getIerarchyDAO().getAllIerarchies();
            for (int a = 0; a < i_add.size(); a++){
                for (int b = 0; b < ies.size(); b++){
                    if (i_add.get(a).getP_id() == ies.get(b).getP_id()){
                        if (i_add.get(a).getP_o() == ies.get(b).getP_o()){
                            if (i_add.get(a).getC_id() != ies.get(b).getC_id()){
                                JOptionPane.showMessageDialog(null, "Выход №" + i_add.get(a).getP_o().toString() + " у " + Factory.getInstance().getValvesDAO().getValveById(i_add.get(a).getP_id()).getv_name().toString() + " уже занят", "Ошибка", JOptionPane.OK_OPTION);
                                return false;
                            }
                        }
                    }
                }
            }
            return true;
        }
        catch (SQLException ex){
            JOptionPane.showMessageDialog(null, "Неизвестная ошибка", "Ошибка", JOptionPane.OK_OPTION);
            return false;
        }
    }

}
